<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>领料单</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="issueNote">
      <search-btn-view immediate btn-text="物料查询" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button type="primary" size="medium" @click="save">领料</el-button>
        </template>
        <div slot="search-content">
          <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:9}" :search="search"
            :search-field="searchField" label-width="100px" input-width="180px">
          </sys-common-search>
        </div>
      </search-btn-view>
      <div class="colorDesc" style="margin-bottom:10px;">
        <span style="color:#999; margin-left:10px">当前订单采购单未审核</span>
        <span style="color:#dd514c;margin-left:10px">当前订单库存数不足</span>
      </div>
      <div class="issue-note-table-div">
        <el-table fit stripe border :data="materialDataList" @selection-change="checkOrder" style="width:100%;" :cell-class-name="getCellClassName"
          height="parent">
          <el-table-column sortable :resizable="false" prop="companyOrderId" label="订单编号" :auto-width="true" min-width="90px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="factoryNo" label="工厂型号" :auto-width="true" min-width="90px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="articleNo" label="客户型号" :auto-width="true" min-width="90px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="providerName" label="供应商" :auto-width="true" min-width="90px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="materialName" label="物料名称" :auto-width="true" min-width="90px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="model" label="规格" :auto-width="true" min-width="80px">
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="color" label="编号" :auto-width="true" min-width="80px">
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="colorDescription" label="描述" :auto-width="true" min-width="90px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="materialDeptName" label="物料部门" :auto-width="true" min-width="100px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="providerNo" label="供方编号" :auto-width="true" min-width="90px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="feedCount" label="投料数" :auto-width="true" min-width="140px"></el-table-column>
          <el-table-column sortable :resizable="false" prop="warehouseCount" label="库存数" :auto-width="true" min-width="140px"></el-table-column>
          <el-table-column :resizable="false" prop="receiveCount" label="领料数" width="150px">
            <template slot-scope="scope">
              <template v-if="scope.row.receiveCount!==null">
                <el-input-number is-decimal-zero size="mini" :controls="false" v-model="scope.row.receiveCount" style="width:110px"
                  :precision="scope.row.precision" :min="1/Math.pow(10,scope.row.precision)" :max="scope.row.receiveMaxCount"
                  @change="receiveCountChange(scope.row)" @click.native.stop>
                </el-input-number>
                {{scope.row.unit}}
              </template>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="feedTotal" label="订单投料数" :auto-width="true" min-width="110px"></el-table-column>
          <el-table-column :resizable="false" prop="selfOutFuCount" label="交接数(付)" width="110px">
            <template slot-scope="scope" v-if="scope.row.selfOutFuCount!==null">
              <div v-if="scope.row.singleFeedCount!==null" style="text-align:center">{{scope.row.selfOutFuCount}}</div>
              <el-input-number v-else size="mini" :controls="false" v-model="scope.row.selfOutFuCount" :min="1" :precision="0" style="width:100px">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="productionUnitFeedCount" label="生产单位投料数" :auto-width="true" min-width="140px">
          </el-table-column>
          <el-table-column sortable :resizable="false" prop="productionUnitCount" label="生产单位库存数" :auto-width="true" min-width="140px">
          </el-table-column>
          <el-table-column :resizable="false" prop="productionUnitReceiveCount" label="生产单位领料数" width="110px">
            <template slot-scope="scope">
              <el-input-number v-if="scope.row.productionUnitReceiveCount!==null" size="mini" :controls="false"
                v-model="scope.row.productionUnitReceiveCount" :min="1" :max="scope.row.productionMaxCount" :precision="0" style="width:100px"
                @click.native.stop>
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="remark" label="备注" width="130px">
            <template slot-scope="scope">
              <el-input v-if="scope.row.isSelect" size="mini" v-model="scope.row.remark" style="width:120px;" @click.native.stop></el-input>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" column-key="selection" type="selection" :selectable="canSelect" width="40px" align="center"
            fixed="right"></el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>
    </div>
  </div>
</body>

<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/vueSystem/components/css/sysCommonSearch.css",
    "/vueSystem/components/css/searchBtnView.css"
  ], [
    "/vueSystem/components/sysCommonSearch.js",
    "/vueSystem/components/searchBtnView.js",
    "/vueSystem/mixins/tablePaginationMixin.js"
  ]);

</script>
<script>
  var app = new Vue({
    el: '#app',
    mixins: [
      tablePaginationMixin()
    ],
    data: function () {
      var search = {
        materialName: '',
        model: '',
        color: '',
        providerName: '',
        companyOrderId: '',
        orderId: '',
        factoryNo: '',
        customerNo: '',
        materialDept: ''
      };
      return {
        loading: false,
        moment: moment,
        materialDataList: [],
        deptAndWorkList: [],
        searchField: ['providerName', 'materialName', 'model', 'color', 'materialDept',
          'companyOrderId', 'orderId', 'factoryNo', 'customerNo'
        ],
        selectFeedList: [],
        materialData: {},
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        user: null
      };
    },
    created: function () {
      this.setUser();
    },
    methods: {
      setUser() {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          self.user = user;
          return user;
        });
      },

      setMaterialDataList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }
        var search = this.search;
        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        }
        postData = this.setPostData(postData, search);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        this.loading = true;
        var self = this;
        ajaxRequest("warehouse/getFeedMaterialData", postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }
          var materialList = res.returnData;
          for (var i = 0; i < materialList.length; i++) {
            var data = materialList[i];
            data.remark = '';
            data.model = data.modal;
            SysUtil.tableSetDeptData(data);

            var precision = SysUtil.getMaterialNumberPrecision(data.unit, 4);
            data.precision = precision;

            var orderId = data.orderId;
            var receiveCount = undefined,
              productionUnitReceiveCount = undefined;
            var isSelect;
            if (data.statusType !== 0) {
              receiveCount = null;
              productionUnitReceiveCount = null;
              isSelect = false;
            } else {
              var warehouseCount = data.warehouseCount,
                productionUnitCount = data.productionUnitCount;
              if (warehouseCount > 0 || productionUnitCount > 0) {
                if (warehouseCount <= 0) {
                  receiveCount = null;
                } else {
                  if (SysUtil.isEmpty(orderId)) {
                    data.receiveMaxCount = warehouseCount;
                  } else {
                    data.receiveMaxCount = _.min([warehouseCount, data.feedCount]);
                  }
                  receiveCount = data.receiveMaxCount;
                }

                if (!SysUtil.isEmpty(orderId)) {
                  if (productionUnitCount <= 0) {
                    productionUnitReceiveCount = null;
                  } else {
                    data.productionMaxCount = _.min([productionUnitCount, data.productionUnitFeedCount]);
                    productionUnitReceiveCount = data.productionMaxCount;
                  }
                } else {
                  productionUnitReceiveCount = null;
                }
                isSelect = receiveCount !== null || productionUnitReceiveCount !== null;
              } else {
                receiveCount = null;
                productionUnitReceiveCount = null;
                isSelect = false;
              }
            }

            var feedCount = data.feedCount;
            var feedTotal = data.feedTotal;
            var singleFeedCount;
            if (SysUtil.isEmpty(feedCount) || SysUtil.isEmpty(feedTotal) || data.type === 2) {
              singleFeedCount = null;
            } else {
              singleFeedCount = feedCount / feedTotal;
            }
            data.singleFeedCount = singleFeedCount;

            if (isSelect && data.unit !== '付' && !SysUtil.isEmpty(orderId)) {
              if (singleFeedCount === null || SysUtil.isEmpty(receiveCount)) {
                data.selfOutFuCount = undefined;
              } else {
                var selfOutFuCount = _.round(receiveCount / singleFeedCount, 4);
                data.selfOutFuCount = Math.floor(selfOutFuCount);
              }
            } else {
              data.selfOutFuCount = null;
            }

            data.receiveCount = receiveCount;
            data.productionUnitReceiveCount = productionUnitReceiveCount;
            data.isSelect = isSelect;
          }
          var dataObject = _.groupBy(materialList, 'materialCode');
          var materialData = {};
          for (var materialCode in dataObject) {
            var materialCodeList = dataObject[materialCode];
            materialData[materialCode] = {
              count: materialCodeList[0].warehouseCount,
              productionUnitCount: materialCodeList[0].productionUnitCount
            };
          }

          self.materialData = materialData;
          self.materialDataList = materialList;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setMaterialDataList(true);
      },

      pageChange: function () {
        this.setMaterialDataList();
      },

      setPostData: function (postData, search) {
        var fields = ['providerName', 'materialName', 'model', 'color', 'companyOrderId', 'orderId', 'factoryNo',
          'customerNo'
        ];
        SysUtil.setPostData(postData, search, fields);
        return postData;
      },
      checkOrder: function (selection) {
        this.selectFeedList = selection;
      },
      receiveCountChange: function (material) {
        var singleFeedCount = material.singleFeedCount;
        if (singleFeedCount === null) {
          return;
        }

        var receiveCount = material.receiveCount;
        if (receiveCount === undefined) {
          material.selfOutFuCount = 0;
          return;
        }

        var selfOutFuCount = receiveCount / singleFeedCount;
        selfOutFuCount = _.round(selfOutFuCount, 4);
        material.selfOutFuCount = Math.floor(selfOutFuCount);
      },
      save: function () {
        var selectFeedList = this.selectFeedList;
        if (selectFeedList.length < 1) {
          this.$alert('请选择需要领取的物料', '信息');
          return;
        }

        var dataList = _.uniqBy(selectFeedList, function (data) {
          if (data.orderId === null) {
            return 0;
          }
          return 1;
        });
        if (dataList.length > 1) {
          this.$alert('投料单领料与物料领料不能一起领', '信息');
          return false;
        }

        var saveDataGroup = _.groupBy(selectFeedList, 'materialCode');
        var materialData = this.materialData;
        for (var materialCode in saveDataGroup) {
          var materialCodeList = saveDataGroup[materialCode];
          var totalCount = _.sumBy(materialCodeList, 'receiveCount');
          if (totalCount > materialData[materialCode].count) {
            this.$alert('物料单位库存不足', '信息');
            return;
          }
          var totalProductionCount = _.sumBy(materialCodeList, 'productionUnitReceiveCount');
          if (totalProductionCount > materialData[materialCode].productionUnitCount) {
            this.$alert('生产单位库存不足', '信息');
            return;
          }
        }

        var postData = [];
        for (var i = 0; i < selectFeedList.length; i++) {
          var data = selectFeedList[i];
          if (!this.checkValid(data)) {
            return;
          }

          var materialPostData = this.getMaterialPostData(data);
          postData.pushArray(materialPostData);
        }

        this.loading = true;
        var self = this;
        ajaxRequest("warehouse/saveWarehouseOut", {
          "metailArray": JSON.stringify(postData)
        }).then(function (msg) {
          self.loading = false;
          self.$alert(msg, '信息');
          self.setMaterialDataList();
        }).catch(function () {
          self.loading = false;
        });
      },
      checkValid: function (material) {
        var orderId = material.orderId;
        var receiveCount = material.receiveCount;
        if (SysUtil.isEmpty(orderId)) {
          if (receiveCount === undefined) {
            this.$alert('请输入领料数', '信息');
            return false;
          }
        } else {
          var productionUnitReceiveCount = material.productionUnitReceiveCount;
          if (productionUnitReceiveCount === null) {
            if (receiveCount === undefined) {
              this.$alert('请输入领料数', '信息');
              return false;
            }
          } else if (receiveCount === null) {
            if (productionUnitReceiveCount === undefined) {
              this.$alert('请输入生产单位领料数', '信息');
              return false;
            }
          } else {
            if (receiveCount === undefined && productionUnitReceiveCount === undefined) {
              this.$alert('领料数与生产单位领料数不能同时为空', '信息');
              return false;
            }
          }

          if (material.selfOutFuCount !== null) {
            if (SysUtil.isEmpty(material.selfOutFuCount)) {
              this.$alert("请输入交接数量", "信息");
              return false;
            }
          }
        }
        return true;
      },
      getMaterialPostData: function (material) {
        var user = this.user;
        var deptId = user.deptId;
        if (SysUtil.isEmpty(deptId) || deptId === '0') {
          deptId = '';
        }

        var workShopId = user.workShopId;
        if (SysUtil.isEmpty(workShopId) || workShopId === '0') {
          workShopId = '';
        }

        var postDataList = [];
        var postData = {
          sourceType: 0,
          warehouseType: 4,
          deptId: deptId,
          workShopId: workShopId
        };

        var fields = ['materialCode', 'materialName', 'materialType', 'providerName', 'model', 'color',
          'remark'
        ];

        if (SysUtil.isEmpty(material.orderId)) {
          postData.count = material.receiveCount;
          postData.type = 5;
          postData.isProductionUnit = 0;
          SysUtil.setPostData(postData, material, fields, false, true);
          postDataList.push(postData);
        } else {
          postData.type = 2;
          postData.feedOrder = material.id;
          postData.orderId = material.orderId;
          postData.rowIndex = material.lineNo;
          SysUtil.setPostData(postData, material, fields, false, true);

          var receiveCount = material.receiveCount;
          if (!SysUtil.isEmpty(receiveCount)) {
            var obj = _.cloneDeep(postData);
            obj.count = receiveCount;
            obj.isProductionUnit = 0;
            var selfOutFuCount = material.selfOutFuCount;
            obj.selfOutFuCount = selfOutFuCount ? selfOutFuCount : 0;
            postDataList.push(obj);
          }

          var productionUnitReceiveCount = material.productionUnitReceiveCount;
          if (!SysUtil.isEmpty(productionUnitReceiveCount)) {
            var obj = _.cloneDeep(postData);
            obj.count = productionUnitReceiveCount;
            obj.isProductionUnit = 1;
            postDataList.push(obj);
          }
        }
        return postDataList;
      },
      canSelect: function (material) {
        return material.isSelect;
      },
      getCellClassName: function (option) {
        var column = option.column;
        var columnKey = column.columnKey;
        if (columnKey !== 'selection') {
          return;
        }
        var material = option.row;
        if (material.statusType === 1) {
          return 'purchaseOrderNotApproval';
        }
        if (material.warehouseCount <= 0 && material.productionUnitCount <= 0) {
          return 'materialCountIsNull';
        }
        return;
      }
    },
    components: {
      SysCommonSearch: SysCommonSearch,
      SearchBtnView: SearchBtnView
    }
  });

</script>
<style>
  .issueNote {
    padding: 10px 20px 5px;
    height: calc(100% - 15px);
    display: flex;
    flex-direction: column;
  }

  .issueNote .issue-note-table-div {
    flex: 1;
    overflow: auto;
  }

  .issueNote .purchaseOrderNotApproval {
    background: #999;
  }

  .issueNote .materialCountIsNull {
    background: #dd514c;
  }

</style>

</html>
